package cn.saltice.idempotence.idem.store;

import cn.saltice.idempotence.idem.enums.IdempotentStorageTypeEnum;
import cn.saltice.idempotence.idem.enums.ReadWriteTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @program: idempotence
 * @description: redis存储实现
 * @author: Mr.Liu
 * @create: 2020-10-04 23:05
 **/
@Slf4j
@Component("IdempotentRedisStorage")
public class IdempotentRedisStorage implements IdempotentStorage{
    @Autowired
    private RedissonClient redissonClient;
    @Override
    public IdempotentStorageTypeEnum type() {
        return IdempotentStorageTypeEnum.REDIS;
    }

    @Override
    public String getValue(String key) {
        RBucket<String> bucket = redissonClient.getBucket(key);
        if (bucket != null){
            String o = bucket.get();
            log.debug("Redis Get key:{},Value:{}",key,o);
            return o;
        }
        return null;
    }

    @Override
    public boolean setValue(String key, String value, int expireTime, TimeUnit timeUnit) {
        log.debug("Redis Set key:{},Value:{},expireTime:{},timeUnit:{}",key,value,expireTime,timeUnit);
        RBucket<Object> bucket = redissonClient.getBucket(key);
        if (bucket != null){
            bucket.set(value,expireTime,timeUnit);
            return true;
        }
        return false;
    }
}
